package top.heue.temp.util.preference

import android.content.Context
import android.widget.LinearLayout
import androidx.annotation.Keep
import androidx.annotation.StringRes
import com.orhanobut.hawk.Hawk
import top.heue.temp.databinding.ToolbarPreferenceBinding
import top.heue.utils.FC
import top.heue.utils.base.helper.inflate
import top.heue.utils.container.ContainActivity
import top.heue.utils.container.ContainCallback
import top.heue.utils.container.ContainConfig

object PreferenceUtil {
    fun start(
        context: Context,
        preferenceClass: Class<*>,
        @StringRes title: Int,
        showBack: Boolean = false
    ) {
        FC.startFragment(context, preferenceClass) {
            isFit = true
            callbackClass = PreferenceCallback::class.java
            tag = Hawk.serialize(arrayOf(title.toString(), showBack.toString()))
        }
    }
}

@Keep
class PreferenceCallback(activity: ContainActivity, config: ContainConfig) :
    ContainCallback(activity, config) {
    private val toolbar: ToolbarPreferenceBinding by activity.inflate {
        val info: Array<String> = Hawk.deserialize(config.tag)
        title = activity.getString(info[0].toInt())
        toolbar.setNavigationOnClickListener {
            activity.finish()
        }
        if (!info[1].toBoolean())
            toolbar.navigationIcon = null
    }

    override fun onSucceed() {
        super.onSucceed()
        val layout = activity.findViewById<LinearLayout>(top.heue.utils.base.R.id.layout_container)
        layout.addView(toolbar.root, 0)
    }
}